<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">

      <el-form-item label="校区" prop="schoolName">
        <el-input v-model="queryParams.schoolName" readonly="readonly" @click.native="openSelectSchool(1)"
          placeholder="请输入校区" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="续费周期" prop="calcMonth">
        <el-input v-model="queryParams.calcMonth" placeholder="请输入续费周期如(2025Q3)" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="支付" prop="payState">
        <el-select v-model="queryParams.payState" placeholder="请选择" clearable>
          <el-option v-for="dict in dict.type.common_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">

      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['report:pay:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-edit" size="mini" :disabled="multiple" @click="handleConfirm"
          v-hasPermi="['report:pay:confirm']">确认收款</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="payList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="续费周期" align="center" prop="calcMonth">
      </el-table-column>
      <el-table-column label="学校全称" align="center" prop="schoolName" />
      <el-table-column label="招生人数" align="center" prop="stuNum" />

      <el-table-column label="续费类型" align="center" prop="renewType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.stu_member_type" :value="scope.row.renewType" />
        </template>
      </el-table-column>
      <el-table-column label="付款状态" align="center" prop="payState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.common_state" :value="scope.row.payState" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="新招">
        <el-table-column label="总人数" align="center" prop="addStuNum" />
        <el-table-column label="总佣金(元)" align="center" prop="addStuAmount" />
      </el-table-column>

      <el-table-column align="center" label="续费">
        <el-table-column label="总人数" align="center" prop="renewStuNum" />
        <el-table-column label="总佣金(元)" align="center" prop="renewStuAmount" />
      </el-table-column>
      <el-table-column label="总佣金(元)" align="center" prop="amount" />
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改(教育-学校)收费订单_付款对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="计费开始日期" prop="startDate">
          <el-date-picker clearable v-model="form.startDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择计费开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计费结束日期" prop="endDate">
          <el-date-picker clearable v-model="form.endDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择计费结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="学校ID" prop="schoolId">
          <el-input v-model="form.schoolId" placeholder="请输入学校ID" />
        </el-form-item>
        <el-form-item label="实际付款金额(分)" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入实际付款金额(分)" />
        </el-form-item>
        <el-form-item label="收款确认人" prop="doUserId">
          <el-input v-model="form.doUserId" placeholder="请输入收款确认人" />
        </el-form-item>
        <el-form-item label="收款备注" prop="doRemark">
          <el-input v-model="form.doRemark" placeholder="请输入收款备注" />
        </el-form-item>
        <el-form-item label="付费状态 1-未付款 0-已付款" prop="payState">
          <el-input v-model="form.payState" placeholder="请输入付费状态 1-未付款 0-已付款" />
        </el-form-item>
        <el-form-item label="收款确认时间" prop="doTime">
          <el-date-picker clearable v-model="form.doTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择收款确认时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="逻辑删除(0：未删除 1：id)" prop="deleted">
          <el-input v-model="form.deleted" placeholder="请输入逻辑删除(0：未删除 1：id)" />
        </el-form-item>
        <el-form-item label="计费年月" prop="calcMonth">
          <el-input v-model="form.calcMonth" placeholder="请输入计费年月" />
        </el-form-item>
        <el-form-item label="学生数" prop="stuNum">
          <el-input v-model="form.stuNum" placeholder="请输入学生数" />
        </el-form-item>
        <el-form-item label="新增学生数量" prop="addStuNum">
          <el-input v-model="form.addStuNum" placeholder="请输入新增学生数量" />
        </el-form-item>
        <el-form-item label="新增学生金额" prop="addStuAmount">
          <el-input v-model="form.addStuAmount" placeholder="请输入新增学生金额" />
        </el-form-item>
        <el-form-item label="续费学生数量" prop="renewStuNum">
          <el-input v-model="form.renewStuNum" placeholder="请输入续费学生数量" />
        </el-form-item>
        <el-form-item label="续费学生金额" prop="renewStuAmount">
          <el-input v-model="form.renewStuAmount" placeholder="请输入续费学生金额" />
        </el-form-item>
        <el-form-item label="实际付款" prop="actAmount">
          <el-input v-model="form.actAmount" placeholder="请输入实际付款" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" @keyup.enter.native="submitForm"
          :loading="submitLoading">{{ submitLoading ? '提交中...' : '确定' }}</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 选择校区 -->
    <SelectSchool ref="selectSchool" :open="selectFlag" @selected-data="selectSchoolData"
      @close-select-window="closeSelectSchool" />
  </div>
</template>

<script>
  import {
    listPay,
    getPay,
    delPay,
    addPay,
    updatePay,
    confirmOrder
  } from "@/api/bus_web/report/pay";
  import SelectSchool from "../../school/schoolinfo/select.vue"
  import {
    mapState
  } from 'vuex';
  import store from "@/store";
  import {
    getToken
  } from "@/utils/auth"
  export default {
    name: "Pay",
    dicts: ['stu_member_type', 'common_state'],
    components: {
      SelectSchool
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 是否显示校区选择
        selectFlag: false,

        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 提交处理中标记
        submitLoading: false,
        // 总条数
        total: 0,
        // (教育-学校)收费订单_付款表格数据
        payList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          startDate: null,
          endDate: null,
          schoolId: null,
          amount: null,
          doUserId: null,
          doRemark: null,
          payState: null,
          doTime: null,
          gmtCreate: null,
          gmtModify: null,
          deleted: null,
          calcMonth: null,
          stuNum: null,
          addStuNum: null,
          addStuAmount: null,
          renewStuNum: null,
          renewStuAmount: null,
          renewType: null,
          actAmount: null
        },
        // 表单参数
        form: {},
        // 导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: {
            Authorization: getToken()
          },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/report/pay/importData"
        },
        // 表单校验
        rules: {
          gmtCreate: [{
            required: true,
            message: "添加时间不能为空",
            trigger: "blur"
          }],
          gmtModify: [{
            required: true,
            message: "更新时间不能为空",
            trigger: "blur"
          }],
          deleted: [{
            required: true,
            message: "逻辑删除(0：未删除 1：id)不能为空",
            trigger: "blur"
          }],
        }
      };
    },
    computed: {
      ...mapState({
        school: state => state.selectSchool.school,
        schoolSelectModel: state => state.selectSchool.schoolSelectModel,
      })
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询(教育-学校)收费订单_付款列表 */
      getList() {
        this.loading = true;
        listPay(this.queryParams).then(response => {
          this.payList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          startDate: null,
          endDate: null,
          schoolId: null,
          amount: null,
          doUserId: null,
          doRemark: null,
          payState: null,
          doTime: null,
          gmtCreate: null,
          gmtModify: null,
          deleted: null,
          createBy: null,
          updateBy: null,
          calcMonth: null,
          stuNum: null,
          addStuNum: null,
          addStuAmount: null,
          renewStuNum: null,
          renewStuAmount: null,
          renewType: null,
          actAmount: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.queryParams.schoolIdArray = []
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加(教育-学校)收费订单_付款";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getPay(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改(教育-学校)收费订单_付款";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.submitLoading = true
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updatePay(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.submitLoading = false
              })
            } else {
              addPay(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.submitLoading = false
              })
            }
          } else {
            this.submitLoading = false
          }
        });
      },
      /**确认收款*/
      handleConfirm(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否更改收费订单编号为"' + ids + '"的数据为已收款？').then(function() {
          return confirmOrder(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("确认收款成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('report/pay/export', {
          ...this.queryParams
        }, `pay_${new Date().getTime()}.xlsx`)
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "账单导入"
        this.upload.open = true
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false
        this.upload.isUploading = false
        this.$refs.upload.clearFiles()
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response
          .message + "</div>", "导入结果", {
            dangerouslyUseHTMLString: true
          })
        this.getList()
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit()
      },
      //选择校区
      openSelectSchool(selectVal) {
        this.selectFlag = true

        // selectVal =1 查询模式 =2 创建、修改模式
        this.$store.dispatch('selectSchool/cleanSchool')
        this.$store.dispatch('selectSchool/setSchoolSelectModel', selectVal)
      },
      closeSelectSchool() {
        this.selectFlag = false
      },
      //确定校区
      selectSchoolData() {
        this.closeSelectSchool()
        if (this.schoolSelectModel == 2) {
          this.form.schoolName = this.school[0].schoolName
          this.form.schoolId = this.school[0].id
          this.$refs.form.clearValidate(['schoolName']);
        } else {
          this.queryParams.schoolName = this.school.map(item => item.schoolName).join(',')
          this.queryParams.schoolIdArray = this.school.map(item => item.id)
        }
        this.$store.dispatch('selectSchool/cleanSchool')
      }
    }
  };
</script>
